<template>
  <view class="content_page">
    <div class="add_item flex_between">
      <div class="title"
        :style="{ fontSize: globalFont == 'small_font' ? '28rpx' : globalFont == 'small-medium' ? '32rpx' : '36rpx' }">计划名称
      </div>
      <div class="choose_modal">
        <up-input placeholder="请输入内容" border="none" v-model="formData.planName" input-align="right"></up-input>
      </div>
    </div>
    <div class="add_item flex_between" @click="showModal('startTime')">
      <div class="title"
        :style="{ fontSize: globalFont == 'small_font' ? '28rpx' : globalFont == 'small-medium' ? '32rpx' : '35rpx' }">开始时间
      </div>
      <div class="choose_modal"
        :style="{ fontSize: globalFont == 'small_font' ? '28rpx' : globalFont == 'small-medium' ? '32rpx' : '35rpx' }">
        {{
          formData.startTime == "00:00" ? "请选择开始时间" : formData.startTime
        }}
        <image src="/static/home/toPage.png"></image>
      </div>
    </div>
    <div class="add_item flex_between" @click="showModal('endTime')" v-if="formData.sprayModel != 2">
      <div class="title"
        :style="{ fontSize: globalFont == 'small_font' ? '28rpx' : globalFont == 'small-medium' ? '32rpx' : '36rpx' }">结束时间
      </div>
      <div class="choose_modal"
        :style="{ fontSize: globalFont == 'small_font' ? '28rpx' : globalFont == 'small-medium' ? '32rpx' : '35rpx' }">
        {{
          formData.endTime == "00:00" || formData.endTime == "null"
            ? "请选择结束时间"
            : formData.endTime
        }}
        <image src="/static/home/toPage.png"></image>
      </div>
    </div>
    <div class="add_item" v-if="formData.sprayModel == 2">
      <div class="title"
        :style="{ fontSize: globalFont == 'small_font' ? '28rpx' : globalFont == 'small-medium' ? '32rpx' : '36rpx' }">驱蚊时长
      </div>
      <div class="choose_modal flex_between">
        <div class="choose_modal_time" :class="{ activeTime: activeTime == i.title }"
          :style="{ fontSize: globalFont == 'small_font' ? '28rpx' : globalFont == 'small-medium' ? '32rpx' : '36rpx' }"
          v-for="(i, k) in MosquitoTime" :key="k" @click="chooseTime(i)">
          {{ i.title }}分钟
          <div class="activeimg" v-if="activeTime == i.title">
            <image src="/static/home/icon_Selected.png"></image>
          </div>
        </div>
      </div>
    </div>
    <div class="add_item">
      <div class="title"
        :style="{ fontSize: globalFont == 'small_font' ? '28rpx' : globalFont == 'small-medium' ? '32rpx' : '36rpx' }">周历计划
      </div>
      <div class="choose_modal flex_between">
        <div class="choose_modal_item" :class="{ activeWeek: i.isSelected }"
          :style="{ fontSize: globalFont == 'small_font' ? '28rpx' : globalFont == 'small-medium' ? '32rpx' : '36rpx' }"
          v-for="(i, k) in weekPlan" :key="k" @click="chooseWeek(i)">
          {{ i.title }}
        </div>
      </div>
    </div>
    <div class="add_item flex_between" @click="showModalTwo('workTime')" v-if="formData.sprayModel != 2">
      <div class="title"
        :style="{ fontSize: globalFont == 'small_font' ? '28rpx' : globalFont == 'small-medium' ? '32rpx' : '36rpx' }">{{
          handleSort[formData.sprayModel] }}</div>
      <div class="choose_modal"
        :style="{ fontSize: globalFont == 'small_font' ? '28rpx' : globalFont == 'small-medium' ? '32rpx' : '35rpx' }">
        {{
          formData.workTime == ""
            ? `请选择${handleSort[formData.sprayModel]}`
            : formData.workTime
        }}
        <image src="/static/home/toPage.png"></image>
      </div>
    </div>
    <div class="add_item flex_between" @click="showModalTwo('restTime')" v-if="formData.sprayModel != 2">
      <div class="title"
        :style="{ fontSize: globalFont == 'small_font' ? '28rpx' : globalFont == 'small-medium' ? '32rpx' : '36rpx' }">间歇时长
      </div>
      <div class="choose_modal"
        :style="{ fontSize: globalFont == 'small_font' ? '28rpx' : globalFont == 'small-medium' ? '32rpx' : '36rpx' }">
        {{ formData.restTime == "" ? "请选择间歇时长" : formData.restTime }}
        <image src="/static/home/toPage.png"></image>
      </div>
    </div>
    <div class="add_item flex_between">
      <div class="title"
        :style="{ fontSize: globalFont == 'small_font' ? '32rpx' : globalFont == 'small-medium' ? '36rpx' : '40rpx' }">开启状态
      </div>
      <div class="choose_modal">
        <up-switch v-model="formData.enableStatus" activeColor="#006D56"></up-switch>
      </div>
    </div>
    <div class="save_btn" @click="toSave"
      :style="{ fontSize: globalFont == 'small_font' ? '28rpx' : globalFont == 'small-medium' ? '32rpx' : '36rpx' }">保存
    </div>
  </view>
  <!-- 开始时间结束时间（23小时59分钟） -->
  <up-popup :show="showWorkTime" z-index="999999999" mode="bottom" :round="16">
    <view class="title addtitle">
      <div style="width: 40rpx"></div>
      <text>{{ showWorkTitle }}</text>
      <image src="/static/home/close.png" @click="showWorkTime = false"></image>
    </view>
    <view class="part borderLine mt114">
      <up-datetime-picker ref="uPickerRefOne" :show="showWorkTime" v-model="formData[oneType]" mode="time"
        :showToolbar="false" :formatter="formatter">
      </up-datetime-picker>
      <view class="modalBtn">
        <view class="btn" @click="confirmOne">确认</view>
      </view>
    </view>
  </up-popup>
  <!-- 降温/雾森时长和间歇时长 -->
  <up-popup :show="showDurtionTime" z-index="999999999" mode="bottom" :round="16">
    <view class="title addtitle">
      <div style="width: 40rpx"></div>
      <text>{{ showDurtionTitle }}</text>
      <image src="/static/home/close.png" @click="showDurtionTime = false"></image>
    </view>
    <view class="part borderLine mt114">
      <up-picker :show="showDurtionTime" ref="uPickerRefTwo" :columns="columns" keyName="value" :defaultIndex="typeTwo == 'workTime' ? workDurtionValue : resetDurationValue
        "></up-picker>
      <view class="modalBtn">
        <view class="btn" @click="confirmTwo">确认</view>
      </view>
    </view>
  </up-popup>
</template>

<script lang="ts" setup>
import { ref, getCurrentInstance } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import { columns, weekPlanList } from "@/utils/configData.ts";
import type { addeditPlanType, resdetailType } from "@/api/detail/type.ts";
import { deviceplanEdit } from "@/api/detail/detail.ts";
import { createDocumentRegistry } from "typescript";
const weekPlan = ref<{ id: number; title: string; isSelected: boolean }[]>([]);
const MosquitoTime = ref<{ id: number; title: string }[]>([
  {
    id: 1,
    title: "1",
  },
  {
    id: 2,
    title: "2",
  },
  {
    id: 3,
    title: "3",
  },
]);
// 表单数据
const formData = ref<addeditPlanType>({
  equipmentId: 0,
  sprayModel: "",
  startTime: "00:00",
  endTime: "00:00",
  workday: "",
  workTime: "",
  restTime: "",
  planName: "",
  planId: 0,
  enableStatus: true,
});
// 工作时长(开始时间/结束时间)
const showWorkTime = ref<boolean>(false);
const formatter = (type: any, value: any) => {
  if (type === "hour") {
    return `${value}时`;
  }
  if (type === "minute") {
    // 分钟正常显示
    return `${value}分`;
  }
  return value;
};
const showWorkTitle = ref<string>("");
const uPickerRefOne = ref<any>(null);
const oneType = ref<string>("");
const showModal = (type: string) => {
  showWorkTitle.value =
    type == "startTime" ? "请选择开始时间" : "请选择结束时间";
  oneType.value = type;
  showWorkTime.value = true;
};
const confirmOne = () => {
  if (oneType.value == "startTime") {
    formData.value.startTime = uPickerRefOne.value.innerValue;
    console.log(formData.value.startTime);
  } else {
    formData.value.endTime = uPickerRefOne.value.innerValue;
  }
  showWorkTime.value = false;
};
// 降温时长和间歇时长
const showDurtionTime = ref<boolean>(false);
const workDurtionValue = ref<any>([]);
const resetDurationValue = ref<any>([]);
const uPickerRefTwo = ref<any>(null);
const showDurtionTitle = ref<string>("");
const typeTwo = ref<string>("");
const showModalTwo = (type: string) => {
  showDurtionTime.value = true;
  typeTwo.value = type;
  showDurtionTitle.value =
    type == "workTime"
      ? `${handleSort[formData.value.sprayModel]}`
      : "请选择间歇时长";
  const defaultIndex = "01:00";
  const defaultIndexTwo = "00:20";
  if (!formData.value.workTime) {
    workDurtionValue.value = defaultIndex
      .split(":")
      .map((f: string) => parseInt(f, 10));
  }
  if (!formData.value.restTime) {
    resetDurationValue.value = defaultIndexTwo
      .split(":")
      .map((f: string) => parseInt(f, 10));
  }
};
const confirmTwo = () => {
  if (typeTwo.value == "workTime") {
    workDurtionValue.value = uPickerRefTwo.value.innerIndex;
    formData.value.workTime = uPickerRefTwo.value.innerIndex
      .map((f: any) => (f < 10 ? `0${f}` : f))
      .join(":");
    const seconds = workDurtionValue.value[0] * 60 + workDurtionValue.value[1];
    if (seconds < 20) {
      uni.showToast({
        title: `${handleSort[formData.value.sprayModel]}不能小于20秒`,
        icon: "none",
      });
      return
    }
  } else {
    resetDurationValue.value = uPickerRefTwo.value.innerIndex;
    formData.value.restTime = uPickerRefTwo.value.innerIndex
      .map((f: any) => (f < 10 ? `0${f}` : f))
      .join(":");
    const seconds = resetDurationValue.value[0] * 60 + resetDurationValue.value[1];
    if (seconds < 20) {
      uni.showToast({
        title: "间歇时长不能小于20秒",
        icon: "none",
      });
      return
    }
  }
  showDurtionTime.value = false;
};
// 周历计划
const chooseWeek = (i: { id: number; title: string; isSelected: boolean }) => {
  i.isSelected = !i.isSelected;
  const dataList = weekPlan.value
    .filter((i: any) => i.isSelected)
    .map((k: any) => k.id)
    .toString()
    .split(",")
    .join(";");
  formData.value.workday = dataList;
};
// 选择驱蚊时长
const activeTime = ref("1");
const chooseTime = (i: { id: number; title: string }) => {
  activeTime.value = i.title;
  formData.value.workTime = activeTime.value;
  console.log(formData.value.workTime, 'formData.value.workTime');
};
const debance = ref(false);
const timeHandle = (str: string) => {
  const [hour, minute] = str.split(":").map(Number);
  const totalMinutes = hour * 60 + minute;
  return totalMinutes;
};
const toSave = () => {
  const startTime = timeHandle(formData.value.startTime);
  const endTime = timeHandle(formData.value.endTime);
  if (startTime == 0) {
    uni.showToast({
      title: "请选择开始时间",
      icon: "none",
    });
    return;
  }
  if (formData.value.sprayModel !== "2") {
    if (startTime !== 0 && startTime >= endTime) {
      uni.showToast({
        title: "结束时间不能小于结束时间，请重新选择",
        icon: "none",
      });
      return;
    }
  }
  if (!formData.value.workday) {
    uni.showToast({
      title: "请选择周历计划",
      icon: "none",
    });
    return;
  }
  // 雾森/降温/驱蚊的20s限制
  const seconds = workDurtionValue.value[0] * 60 + workDurtionValue.value[1];
  if (seconds < 20) {
    uni.showToast({
      title: `${handleSort[formData.value.sprayModel]}不能小于20秒`,
      icon: "none",
    });
    return
  }
  // 间歇时长的限制
  if (formData.value.sprayModel !== '2') {
    if (!formData.value.restTime) {
      uni.showToast({
        title: "请选择间歇时长",
        icon: "none",
      });
      return
    }
  }

  const secondsTwo = resetDurationValue.value[0] * 60 + resetDurationValue.value[1];
  if (formData.value.sprayModel !== '2') {
    if (secondsTwo < 20) {
      uni.showToast({
        title: "间歇时长不能小于20秒",
        icon: "none",
      });
      return
    }
  }

  if (debance.value) {
    return;
  }
  debance.value = true;
  const arrMap = {
    '1': '雾森计划',
    '2': "驱蚊计划",
    '6': '降温计划'
  }
  const planName = arrMap[formData.value.sprayModel];
  const defaultPlanName = `${planName}${planListLength.value + 1}`;
  uni.showLoading({
    title: "操作中...",
    icon: "none",
  });

  const data = {
    equipmentId: formData.value.equipmentId,
    sprayModel: formData.value.sprayModel,
    planId: formData.value.planId,
    planName: formData.value.planName || defaultPlanName,
    startTime: formData.value.startTime + ":00",
    endTime:
      formData.value.sprayModel != "2"
        ? formData.value.endTime + ":00"
        : undefined,
    workTime:
      formData.value.sprayModel != "2"
        ? formData.value.workTime
        : `0${formData.value.workTime}:00`,
    restTime:
      formData.value.sprayModel != "2" ? formData.value.restTime : undefined,
    workday: formData.value.workday,
    enableStatus: formData.value.enableStatus,
  };
  deviceplanEdit(data)
    .then((res: resdetailType) => {
      if (res.resultStatus) {
        uni.showToast({
          title: "操作成功",
          icon: "none",
          duration: 2500,
        });
        uni.reLaunch({
          url: `/pages/setDevice/settingPage?currentTab=1&currentSprayModal=${formData.value.sprayModel}`,
        });
      } else {
        uni.showToast({
          title: res.errorMessage,
          icon: "none",
          duration: 2500,
        });
        // if (res.errorCode !== "300205") {
        //     uni.reLaunch({
        //       url: `/pages/setDevice/settingPage?currentTab=1&currentSprayModal=${formData.value.sprayModel}`,
        //     });
        // }
      }
    })
    .catch((err: any) => {
      uni.showToast({
        title: "服务器异常",
        icon: "none",
      });
      // uni.reLaunch({
      //   url: `/pages/setDevice/settingPage?currentTab=1&currentSprayModal=${formData.value.sprayModel}`,
      // });
    })
    .finally(() => {
      setTimeout(() => {
        uni.hideLoading();
        debance.value = false;
      }, 500);
    });
};
// 编辑的时候的数据
const getEditData = (options: any) => {
  formData.value.sprayModel = options.sprayModel;
  formData.value.planName = options.planName;
  formData.value.planId = Number(options.planId);
  formData.value.startTime = options.startTime?.slice(0, 5);
  formData.value.endTime = options.endTime?.slice(0, 5);
  formData.value.workday = options.workday;
  formData.value.enableStatus = options.enableStatus === "true";
  const arr = formData.value.workday.split(";").map(Number);
  // 先重置清空再进行赋值
  weekPlan.value.forEach((k) => {
    k.isSelected = false;
  });
  weekPlan.value.forEach((num) => {
    if (arr.includes(num.id)) {
      num.isSelected = true;
    }
  });
  if (formData.value.sprayModel == "2") {
    formData.value.workTime = options.workTime.split(":")[0];
    activeTime.value = formData.value.workTime;
  } else {
    formData.value.workTime = options.workTime
      .split(":")
      .map((f: any) => f.padStart(2, "0"))
      .join(":");
  }
  workDurtionValue.value = formData.value.workTime
    .split(":")
    .map((f: string) => parseInt(f, 10));
  formData.value.restTime = options.restTime
    .split(":")
    .map((f: any) => f.padStart(2, "0"))
    .join(":");
  resetDurationValue.value = formData.value.restTime
    .split(":")
    .map((f: string) => parseInt(f, 10));
};
const handleSort: { [key: string]: string } = {
  "1": "雾森时长",
  "2": "驱蚊时长",
  "6": "降温时长",
};
const planListLength = ref()
const instance = getCurrentInstance();
const appStorage = instance?.appContext.config.globalProperties.appStorage;
const globalFont = ref()
onLoad((options: any) => {  
  const userInfo_key = appStorage.getObj("userInfo_key");
  globalFont.value = userInfo_key.smallFont
  weekPlan.value = weekPlanList;
  formData.value.equipmentId = options.equipmentId;
  formData.value.sprayModel = options.sprayModel;
  if (formData.value.sprayModel == "2") {
    formData.value.workTime = "1";
  }
  weekPlan.value.forEach((k) => {
    k.isSelected = false;
  });
  if (options.planId != 0) {
    uni.setNavigationBarTitle({
      title: "编辑计划",
    });
    getEditData(options);
    planListLength.value = Number(options.index)
  } else {
    planListLength.value = Number(options.length)
  }
});
</script>

<style lang="scss" scoped>
.content_page {
  height: calc(100vh - 88rpx);
  background-color: #fff;
  padding: 0 38rpx;

  .add_item {
    padding: 32rpx 0;
    border-bottom: 2rpx solid #eeeeee;

    .title {
      // font-size: 30rpx;
      color: #333;
      font-weight: 600;
    }

    .choose_modal {
      margin-top: 20rpx;
      display: flex;
      align-items: center;

      image {
        width: 24rpx;
        height: 24rpx;
        margin-left: 20rpx;
      }

      .choose_modal_item {
        width: 82rpx;
        height: 84rpx;
        background: #fff;
        border-radius: 16rpx;
        border: 2rpx solid #efefef;
        line-height: 84rpx;
        color: #333;
        text-align: center;
        // font-size: 28rpx;
      }

      .activeWeek {
        width: 82rpx;
        height: 84rpx;
        background: #00a57d;
        border-radius: 16rpx;
        line-height: 84rpx;
        color: #fff;
        text-align: center;
        // font-size: 28rpx;
      }

      .choose_modal_time {
        width: 210rpx;
        height: 84rpx;
        background: #fff;
        border-radius: 16rpx;
        border: 2rpx solid #efefef;
        line-height: 84rpx;
        color: #333;
        text-align: center;
        // font-size: 28rpx;
        position: relative;
      }

      .activeimg {
        image {
          position: absolute;
          top: 0;
          right: 0;
        }
      }

      .activeTime {
        width: 210rpx;
        height: 84rpx;
        border: 2rpx solid #00a57d;
        border-radius: 16rpx;
        line-height: 84rpx;
        text-align: center;
        // font-size: 28rpx;
        color: #333;
      }
    }
  }

  .save_btn {
    height: 88rpx;
    line-height: 88rpx;
    text-align: center;
    color: #fff;
    // font-size: 36rpx;
    background: linear-gradient(90deg, #00a67e, #006d56);
    border-radius: 16rpx;
    margin-top: 300rpx;
  }
}
</style>
<style lang="scss">
// .aaaa {
//   ::v-deep .u-transition.u-fade-enter-to.u-fade-enter-active {
//     display: none !important;
//   }

//   ::v-deep .u-transition.u-slide-up-enter-to.u-slide-up-enter-active {
//     position: inherit !important;
//   }
// }</style>
